<template>
  <div class="app-container device-data">
    <el-card style="width: 100%;height: 100%;">
      <el-form label-width="80px" class="filter-container">
        <el-row>
          <el-col :span="5">
            <el-form-item label="网关">
              <el-select v-model="inputSearchParams.deviceId" placeholder="请选择所属网关" clearable style="width: 100%;">
                <el-option v-for="d in deviceList" :value="d.deviceId" :label="d.deviceName" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="统计类型">
              <el-select v-model="inputSearchParams.statType" placeholder="请选择统计类型" style="width: 100%;">
                <el-option :value="1" label="按小时统计" />
                <el-option :value="2" label="按日统计" />
                <el-option :value="4" label="详细数据" />
                <el-option :value="3" label="按班次（白班：7:30-19:30，夜班：19:30-7:30）" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="时间">
              <div v-show="inputSearchParams.statType == 1">
                <el-date-picker
                  v-model="inputSearchParams.daterange[0]"
                  :clearable="false"
                  style="width: 100%;"
                  type="date"
                />
              </div>
              <div v-show="inputSearchParams.statType == 2 || inputSearchParams.statType == 3">
                <el-date-picker
                  v-model="inputSearchParams.daterange"
                  style="width: 100%;"
                  :clearable="false"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                />
              </div>
              <div v-show="inputSearchParams.statType == 4">
                <el-date-picker
                  v-model="inputSearchParams.daterange"
                  style="width: 100%;"
                  :clearable="false"
                  type="datetimerange"
                  :___default-time="[new Date(0, 0, 0, 0, 0, 0), new Date(0, 0, 0, 23, 59, 59)]"
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="3" style="text-align: center">
            <el-button type="primary" icon="el-icon-search" @click="search">
              查询
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card style="width: 100%;height: 100%;">
      <div v-show="searchParams.statType != 4" ref="chart" style="width: 100%;height: 100%;" />
      <div v-show="searchParams.statType == 4" style="height: 100%;width:100%;display: grid;grid-template-rows: minmax(0, 1fr) auto;">
        <div style="width: 100%;position: relative;">
          <div style="position: absolute;width: 100%;height: 100%;">
            <el-table v-loading="prodLogs == null" :data="prodLogs != null ? prodLogs.content : null" empty-text="无生产数据" border stripe height="100%">
              <el-table-column label="设备" prop="deviceName" align="center" width="170px" show-overflow-tooltip />
              <el-table-column label="模穴数" prop="deviceHoleCount" align="center" />
              <el-table-column label="成型周期时长" align="center" :formatter="l => `${l.devtime}秒`" />
              <el-table-column label="生产周期时长" align="center" :formatter="l => `${l.prdtime}秒`" />
              <el-table-column label="开模时长" align="center" :formatter="l => `${l.opntime}秒`" />
              <el-table-column label="合模时长" align="center" :formatter="l => `${l.clstime}秒`" />
              <el-table-column label="注射时长" align="center" :formatter="l => `${l.injtime}秒`" />
              <el-table-column label="熔胶时长" align="center" :formatter="l => `${l.meltime}秒`" />
              <el-table-column label="冷却时长" align="center" :formatter="l => `${l.cootime}秒`" />
              <el-table-column label="取件时长" align="center" :formatter="l => `${l.gettime}秒`" />
              <el-table-column label="告警" align="center" :formatter="l => l.alarm === 1 ? '是' : '无'" />
              <el-table-column label="时间" prop="createTime" align="center" width="170px" show-overflow-tooltip />
            </el-table>
          </div>
        </div>
        <div v-if="prodLogs != null" style="display: grid;grid-template-columns: minmax(0, 1fr) auto;">
          <div>
            <el-pagination
              :current-page.sync="searchParams.pageNo"
              :page-size.sync="searchParams.pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="prodLogs.totalElements"
              style="padding: 5px 0;"
              @current-change="console.log($event)"
            />
          </div>
          <div class="prop-count">
            ，总生产数量：{{ prodLogs.otherData }}件
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import LineChart from './LineChart'
import * as echarts from 'echarts'
import request from '@/utils/request'
import moment from 'moment'
import httpRequest from '@/utils/request'

export default {
  name: 'DeviceData',
  components: { LineChart },
  data() {
    return {
      console,
      prodLogs: null,
      chartData: null,
      deviceList: null,
      inputSearchParams: {
        deviceId: null,
        statType: 1,
        daterange: [moment().startOf('day').toDate(), moment().endOf('day').toDate()]
      },
      searchParams: {
        deviceId: null,
        statType: null,
        daterange: null,
        pageNo: 1,
        pageSize: 50
      }
    }
  },
  computed: {
    chartOption() {
      if (this.chartData == null) {
        return {}
      }
      let xSeries
      if (this.searchParams.statType == 1) {
        xSeries = this.chartData.map(d => d.x + '时')
      } else {
        xSeries = this.chartData.map(d => d.x + '日')
      }
      let ySeries
      if (this.searchParams.statType == 3) {
        ySeries = [{
          name: '白班生产数量',
          type: 'line',
          data: this.chartData.map(d => d.y1)
        }, {
          name: '夜班生产数量',
          type: 'line',
          data: this.chartData.map(d => d.y2)
        }]
      } else {
        ySeries = [{
          name: '生产数量',
          type: 'line',
          data: this.chartData.map(d => d.y)
        }]
      }
      return {
        backgroundColor: 'rgba(0, 0, 0, 0)',
        grid: {
          top: '8%',
          right: '0%',
          bottom: '5%',
          left: '5%'
        },
        title: {
          text: '生产数量',
          subtext: '单位（件）',
          x: 'left'
        },
        tooltip: {
          trigger: 'axis',
          formatter: datas => {
            if (datas.length == 1) {
              return datas.map(d => `${d.axisValueLabel}${d.seriesName}：${d.data}`)[0]
            } else if (datas.length > 1) {
              return `${datas[0].axisValueLabel}<br>` + datas.map(d => `${d.seriesName}：${d.data}`).join('<br>')
            }
          }
        },
        xAxis: {
          data: xSeries
        },
        yAxis: {
          splitLine: {
            lineStyle: {
              color: 'rgba(255, 255, 255, 0.2)'
            }
          }
        },
        series: ySeries.map(s => ({
          ...s,
          itemStyle: {
            normal: {
              label: {
                show: true, // 开启显示
                position: 'top', // 在上方显示
                formatter(a, b, c, d) {
                  return a.value > 0 ? a.value : ''
                }
              }
            }
          }
        }))
      }
    }
  },
  watch: {
    chartOption: {
      immediate: true,
      deep: true,
      handler() {
        this.$nextTick(() => {
          if (this.$echarts == null) {
            this.$echarts = echarts.init(this.$refs['chart'], 'dark')
          }
          this.$echarts.setOption(this.chartOption)
          this.$nextTick(() => {
            const event = document.createEvent('HTMLEvents')
            event.initEvent('resize', true, true)
            window.dispatchEvent(event)
          })
        })
      }
    },
    'searchParams.statType'() {
      if (this.$echarts != null) {
        this.$echarts.setOption({}, true)
      }
    },
    searchParams: {
      deep: true,
      handler() {
        if (this.searchParams.statType == 4) {
          this.loadProdLogs()
        } else {
          this.loadChartData()
        }
      }
    }
  },
  created() {
    const deviceId = this.$route.query['deviceId']
    if (deviceId != null && deviceId != '') {
      this.inputSearchParams.deviceId = parseInt(deviceId)
    }

    this.loadAllDevice()
    this.search()

    window.addEventListener('resize', () => {
      if (this.$echarts != null) {
        this.$echarts.resize()
      }
    })
  },
  methods: {
    search() {
      this.searchParams = { ...this.searchParams, ...this.inputSearchParams, pageNo: 1, daterange: [...this.inputSearchParams.daterange] }
    },
    loadAllDevice() {
      request({
        url: '/api/device/loadAllDevice'
      }).then(resp => {
        if (resp.success) {
          this.deviceList = resp.data
        } else {
          this.$message.error(resp.message)
        }
      })
    },
    loadProdLogs() {
      if (this.searchParams.daterange == null || this.searchParams.daterange.length != 2) {
        this.$message.warning('请选择时间范围')
        return
      }
      const beginTime = moment(this.searchParams.daterange[0]).format('YYYY-MM-DD HH:mm:ss')
      const endTime = moment(this.searchParams.daterange[1]).format('YYYY-MM-DD HH:mm:ss')

      this.prodLogs = null
      httpRequest({
        url: '/api/datalog/loadDataLog',
        params: {
          deviceId: this.searchParams.deviceId,
          pageSize: this.searchParams.pageSize,
          pageNo: this.searchParams.pageNo - 1,
          beginTime,
          endTime
        }
      }).then(resp => {
        if (resp.success) {
          this.prodLogs = resp.data
        } else {
          this.$message.error(resp.message)
        }
      })
    },
    loadChartData() {
      let beginTime, endTime
      if (this.inputSearchParams.statType == 1) {
        beginTime = moment(this.searchParams.daterange[0]).startOf('day').format('YYYY-MM-DD HH:mm:ss')
        endTime = moment(this.searchParams.daterange[0]).endOf('day').format('YYYY-MM-DD HH:mm:ss')
      } else if (this.inputSearchParams.statType == 2) {
        beginTime = moment(this.searchParams.daterange[0]).startOf('day').format('YYYY-MM-DD HH:mm:ss')
        endTime = moment(this.searchParams.daterange[1]).endOf('day').format('YYYY-MM-DD HH:mm:ss')
      } else if (this.inputSearchParams.statType == 3) {
        beginTime = moment(this.searchParams.daterange[0]).format('YYYY-MM-DD 07:30:00')
        endTime = moment(this.searchParams.daterange[1]).add(1, 'day').format('YYYY-MM-DD 07:29:59')
      }
      request({
        url: '/api/datalog/statProductionCount',
        params: {
          deviceId: this.searchParams.deviceId,
          beginTime: beginTime,
          endTime: endTime,
          statType: this.searchParams.statType
        }
      }).then(resp => {
        if (resp.success) {
          this.chartData = resp.data
        } else {
          this.$message.error(resp.message)
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.device-data {
  background-color: #000228;
  min-height: 100%;

  display: grid;
  grid-template-columns: minmax(0, 1fr);
  grid-template-rows: auto 1fr;
  grid-gap: 10px;
}
</style>

<style lang="scss">
.device-data {
  .el-form-item {
    margin-bottom: 0;

    .el-form-item__label {
      color: #ffffff;
    }
  }

  .el-card {
    background-color: transparent;

    .el-card__body {
      height: 100%;
    }
  }

  .el-table {
    --border-color: rgba(255, 255, 255, 0.3);
    background-color: transparent !important;
    border-color: var(--border-color) !important;

    .el-loading-mask {
      background-color: #000228;
    }

    tr, th, td {
      background-color: transparent !important;
      border-color: var(--border-color) !important;
      color: rgba(255, 255, 255, 0.8);
    }

    &::after,
    &::before {
      background-color: var(--border-color) !important;
    }
  }

  .prop-count,
  .el-pagination__total {
    display: flex;
    font-size: 13px;
    align-items: center;
    color: #FFFFFF;
    margin-right: 0;
  }
}
</style>
